import './App6.css';
import { useEffect, useState , useRef} from 'react'


import { Input, Space, Table, Popconfirm , message , Modal } from 'antd';
const { Search } = Input;


function App() {
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      dataIndex: 'do',
      key: 'do',
      render: (text,record) => (
        <Space size="middle">
          <Popconfirm title="确认删除？" onConfirm={()=> onDelete(record.id)}>
            <a href="#">删除</a>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const [dataSource, setDataSource] = useState([])

  function onDelete(id) {
    fetch('http://localhost:3001/data/'+id, {
      method: 'DELETE'
    }).then((response) => {
      if(response.status === 200) {
        message.success('删除成功')
        setDataSource(dataSource.filter(item => item.id !== id))
      }
    })
  }  
  useEffect(() => {
    fetch('http://localhost:3001/data', {
      method: 'GET'
    }).then((response) => {//取出后端数据，然后展示在前端
      return response.json()
    }).then((data) => {
      console.log(data)
      setDataSource(data)
    })
  }, [])
  const ipt = useRef(null)
  function onSearch(iptValue) {
    //在search框输入要搜索的人名，然后通过匹配模拟数据库中的名字，再返回那一条数据
      fetch('http://localhost:3001/data/?name='+iptValue, {
        method: 'GET'
      }).then((response) => {//取出后端数据，然后展示在前端
        return response.json()
      }).then((data) => {
        console.log(data)
        setDataSource(data)
      })
  }
  return (
    <div className="container">
      <div className="search-box">
        <Search
          placeholder='请输入关键词'
          enterButton="搜索"
          size="large"
          allowClear
          ref={ipt}
          onSearch={onSearch}
        />
      </div>

      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={false}
      />
    </div>
  )
}

export default App;